//
//  CustomPlayerViewController.m
//  CapriceMusic
//
//  Created by 蒋恩浩 on 16/1/9.
//  Copyright © 2016年 MYX. All rights reserved.
//

#import "CustomPlayerViewController.h"

@interface CustomPlayerViewController ()

@property (nonatomic, strong) UISegmentedControl *segment;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *commentDataSource;
@property (nonatomic, strong) DetailModel *detailModel;
// 播放器
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerLayer *playerLayer;
@property (nonatomic, strong) AVPlayerItem *playerItem;
// 控制台
@property (nonatomic, strong) UIView *controlTable;
// 播放暂停
@property (nonatomic, strong) UIButton *playControlButton;
// 进度条
@property (nonatomic, strong) UISlider *progressBar;
@property (nonatomic, strong) NSTimer *timer;
// 时间
@property (nonatomic, assign) NSInteger minutes;
@property (nonatomic, assign) NSInteger seconds;
@property (nonatomic, strong) JEHLabel *timesLabel;
// 全屏
@property (nonatomic, strong) UIButton *outFullScreen;
// 标题
@property (nonatomic, strong) JEHLabel *topLabel;
// 亮度
@property (nonatomic, strong) UIView *leftView;
@property (nonatomic, strong) JEHLabel *lumaLabel;
@property (nonatomic, strong) UIView *lumaView;
// 音量
@property (nonatomic, strong) UIView *rightView;
@property (nonatomic, strong) JEHLabel *volumeLabel;
// 缓冲view
@property (nonatomic, strong) UIView *bufferView;

@end

// 定义全局变量
static CustomPlayerViewController *singlePlayerVC = nil;
static BOOL isActivityViewAppear = NO;

@implementation CustomPlayerViewController

#pragma mark - 创建单例播放器
+ (instancetype)shareSinglePlayerViewController {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        singlePlayerVC = [[CustomPlayerViewController alloc] init];
    });
    return singlePlayerVC;
}

#pragma mark - lifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor blackColor];
    if (self.isLocal == YES) {
        
        NSLog(@"本地视频");
        [self tableOfVideoControl];
        [self createUserActivityView];
        [self localVideoPlayer];
    } else {
        [self tableOfVideoControl];
        [self createUserActivityView];
        [self createPlayerView];
    }
    // 接收删除播放器通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deletePlayer) name:@"DeletePlayer" object:nil];
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 接收删除播放器通知方法
- (void)deletePlayer {
    
    [self.playerLayer removeFromSuperlayer];
}

#pragma mark - 添加交互手势及视图
- (void)createUserActivityView {

    // 标题
    self.topLabel = [[JEHLabel alloc] initWithFrame:CGRectMake(0, 0, self.view.height, 30) withFont:14 withTextColor:[UIColor whiteColor]];
    self.topLabel.alpha = 0;
    self.topLabel.backgroundColor = [UIColor colorWithRed:34 / 255.0 green:34 / 255.0 blue:34 / 255.0 alpha:0.7];
    self.topLabel.textAlignment = NSTextAlignmentCenter;
    self.topLabel.text = self.title;
    // 全屏view调整亮度
    self.lumaView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.height, self.view.width)];
    self.lumaView.backgroundColor = [UIColor blackColor];
    self.lumaView.alpha = 0;
    // 左亮度
    self.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 30, self.view.height / 2, self.view.width - 60)];
    self.lumaLabel = [[JEHLabel alloc] initWithFrame:CGRectMake(20, 60, 90, 20) withFont:13 withTextColor:[UIColor whiteColor]];
    // 右音量
    self.rightView = [[UIView alloc] initWithFrame:CGRectMake(self.view.height / 2, 30, self.view.height / 2, self.view.width - 60)];
    self.volumeLabel = [[JEHLabel alloc] initWithFrame:CGRectMake(self.rightView.height - 90, 60, 90, 20) withFont:13 withTextColor:[UIColor whiteColor]];
    [self.view addSubview:self.lumaView];
    [self.view addSubview:self.topLabel];
    [self.view addSubview:self.leftView];
    [self.view addSubview:self.rightView];
    [self.leftView addSubview:self.lumaLabel];
    [self.rightView addSubview:self.volumeLabel];
    [self.view bringSubviewToFront:self.topLabel];
    [self.view bringSubviewToFront:self.controlTable];
    
    UITapGestureRecognizer *leftTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(appearTap)];
    UITapGestureRecognizer *rightTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(appearTap)];
    [self.leftView addGestureRecognizer:leftTap];
    [self.rightView addGestureRecognizer:rightTap];
    
    UIPanGestureRecognizer *lumaPan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(lumaPan:)];
    [self.leftView addGestureRecognizer:lumaPan];
    
    UIPanGestureRecognizer *volumePan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(volumePan:)];
    [self.rightView addGestureRecognizer:volumePan];
}

#pragma mark - 显示交互点击手势
- (void)appearTap {
    
    if (isActivityViewAppear == NO) {
        
        self.topLabel.alpha = 1;
        self.controlTable.alpha = 1;
        isActivityViewAppear = YES;
    } else {
        self.topLabel.alpha = 0;
        self.controlTable.alpha = 0;
        self.lumaLabel.alpha = 0;
        self.volumeLabel.alpha = 0;
        isActivityViewAppear = NO;
    }
}

#pragma mark - 亮度平移手势
- (void)lumaPan:(UIPanGestureRecognizer *)pan {
    
    CGPoint point = [pan translationInView:self.leftView];
    self.lumaView.alpha = self.lumaView.alpha + (float)point.y / (float)4000;
    if (self.lumaView.alpha > 0.45) {
        
    self.lumaView.alpha = 0.45;
    } else if (self.lumaView.alpha < 0) {
        
    self.lumaView.alpha = 0;
    }
    self.lumaLabel.alpha = 1;
    self.topLabel.alpha = 1;
    self.controlTable.alpha = 1;
    isActivityViewAppear = YES;
    self.lumaLabel.text = [NSString stringWithFormat:@"亮度:%0.0f%%", 100 - self.lumaView.alpha * 2 * 100];
}

#pragma mark - 音量平移手势
- (void)volumePan:(UIPanGestureRecognizer *)pan {
    
    CGPoint point = [pan translationInView:self.rightView];
    self.player.volume = self.player.volume - (float)point.y / (float)2000;
    if (self.player.volume > 1) {
        
        self.player.volume = 1;
    } else if (self.player.volume < 0) {
        
        self.player.volume = 0;
    }
    self.volumeLabel.alpha = 1;
    self.topLabel.alpha = 1;
    self.controlTable.alpha = 1;
    isActivityViewAppear = YES;
    self.volumeLabel.text = [NSString stringWithFormat:@"音量:%0.0f%%", self.player.volume * 100];
}

#pragma mark - 创建播放器视图
- (void)createPlayerView {
    // 导航栏title
    self.navigationItem.title = self.detailModel.title;
    // 播放控制按钮图片
    if (self.playControlFlag == 1) {
        
        [self.playControlButton setImage:[[UIImage imageNamed:@"stop"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    } else {
        [self.playControlButton setImage:[[UIImage imageNamed:@"start"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    }
    // 创建播放器视图
    NSURL *url = [NSURL URLWithString:self.urlString];
    AVAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
    self.playerItem = [AVPlayerItem playerItemWithAsset:asset];
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playerLayer.frame = CGRectMake(0, 0, self.view.layer.frame.size.height, self.view.layer.frame.size.width);
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    [self.view.layer addSublayer:self.playerLayer];
    // 进度条最大值
    self.progressBar.maximumValue = self.videoTimes;
    // 设置当前播放位置
    CMTime playFromTime = CMTimeMake(self.currentValue, 1);
    [self.player seekToTime:playFromTime];
    if (self.playControlFlag == 1) {
        
        [self.player play];
        [self.timer setFireDate:[NSDate distantPast]];
    } else {
        [self.player pause];
        [self.timer setFireDate:[NSDate distantFuture]];
    }
    [self.view bringSubviewToFront:self.lumaView];
    [self.view bringSubviewToFront:self.controlTable];
    [self.view bringSubviewToFront:self.topLabel];
    [self.view bringSubviewToFront:self.rightView];
    [self.view bringSubviewToFront:self.leftView];
}

#pragma mark - 视频控制台
- (void)tableOfVideoControl {
    
    // 添加控制台
    self.controlTable = [[UIView alloc] initWithFrame:CGRectMake(10, self.view.width - 30, self.view.height - 20, 30)];
        self.controlTable.alpha = 0;
    self.controlTable.backgroundColor = [UIColor colorWithRed:34 / 255.0 green:34 / 255.0 blue:34 / 255.0 alpha:0.7];
    [self.view addSubview:self.controlTable];
    // 播放控制按钮
    self.playControlButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.playControlButton.frame = CGRectMake(10, 0, 30, 30);
    [self.playControlButton addTarget:self action:@selector(playControlButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.controlTable addSubview:self.playControlButton];
    // 进度条
    self.progressBar = [[UISlider alloc] initWithFrame:CGRectMake(50, 0, self.controlTable.width - 130 - 50, 30)];
    self.progressBar.minimumValue = 0.0f;
    self.progressBar.minimumTrackTintColor = [UIColor colorWithRed:30 / 255.0 green:195 / 255.0 blue:153 / 255.0 alpha:1.0];
    [self.progressBar setThumbImage:[UIImage imageNamed:@"thumb"] forState:UIControlStateNormal];
    [self.progressBar addTarget:self action:@selector(thumbBeginScroll:) forControlEvents:UIControlEventTouchDown];
    [self.progressBar addTarget:self action:@selector(thumbBeingScroll:) forControlEvents:UIControlEventValueChanged];
    [self.progressBar addTarget:self action:@selector(thumbEndScroll:) forControlEvents:UIControlEventTouchUpInside];
    [self.controlTable addSubview:self.progressBar];
    // 缓冲区view
//    self.bufferView = [UIView alloc] initWithFrame:CGRectMake(0, <#CGFloat y#>, <#CGFloat width#>, <#CGFloat height#>)
    // 进度条timer
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    [self.timer setFireDate:[NSDate distantFuture]];
    // 进度条点击手势
    UITapGestureRecognizer *sliderTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sliderTapAction:)];
    [self.progressBar addGestureRecognizer:sliderTap];
    // 时间label
    self.timesLabel = [[JEHLabel alloc] initWithFrame:CGRectMake(self.controlTable.width - 120, 0, 80, 30) withFont:13 withTextColor:[UIColor whiteColor]];
    [self.controlTable addSubview:self.timesLabel];
    // 退出全屏按钮
    self.outFullScreen = [UIButton buttonWithType:UIButtonTypeCustom];
    self.outFullScreen.frame = CGRectMake(self.controlTable.width - 40, 0, 30, 30);
    [self.outFullScreen setImage:[UIImage imageNamed:@"outFullScreen"] forState:UIControlStateNormal];
    [self.outFullScreen addTarget:self action:@selector(outAllScreenButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.controlTable addSubview:self.outFullScreen];
}

#pragma mark - 缓冲
- (NSTimeInterval)availableDuration {
    
    NSArray *loadedTimeRanges = [[self.player currentItem] loadedTimeRanges];
    // 获取缓冲区域
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    // 计算缓冲总进度
    NSTimeInterval result = startSeconds + durationSeconds;
    return result;
}

#pragma mark - 进度条
- (void)timerAction {
    
    // 计算缓冲进度
    NSTimeInterval timeInterval = [self availableDuration];
    NSLog(@"%f", timeInterval);
    // 获取进度条位置，转换为时间
    self.progressBar.value = CMTimeGetSeconds(self.player.currentItem.currentTime) / CMTimeGetSeconds(self.player.currentItem.duration) * self.videoTimes;
    NSInteger currentMinute = self.progressBar.value / 60;
    NSInteger currentSecond = self.progressBar.value - currentMinute * 60;
    self.minutes = self.videoTimes / 60;
    self.seconds = self.videoTimes - self.minutes * 60;
    // 显示时间（当前时间/总时间）
    self.timesLabel.text = [NSString stringWithFormat:@"%02ld:%02ld/%02ld:%02ld", currentMinute, currentSecond, self.minutes, self.seconds];
    // 播放结束
    if (self.progressBar.value == self.progressBar.maximumValue) {

        [self playControlButtonAction];
    }
}

#pragma mark - 控制台点击手势事件
- (void)tapAction:(UITapGestureRecognizer *)tap {
    
    [self playControlButtonAction];
}

#pragma mark - 播放控制按钮点击事件
- (void)playControlButtonAction {
    
    if (self.progressBar.value == self.progressBar.maximumValue) {
        
        self.timesLabel.text = [NSString stringWithFormat:@"00:00/%02ld:%02ld", self.minutes, self.seconds];
        CMTime playFromTime = CMTimeMake(0, 1);
        [self.player seekToTime:playFromTime];
    }
    if (self.playControlFlag == 1) {
        
        [self.player pause];
        [self.timer setFireDate:[NSDate distantFuture]];
        [self.playControlButton setImage:[UIImage imageNamed:@"start"] forState:UIControlStateNormal];
        self.playControlFlag = 0;
    } else {
        [self.player play];
        [self.timer setFireDate:[NSDate distantPast]];
        [self.playControlButton setImage:[UIImage imageNamed:@"stop"] forState:UIControlStateNormal];
        self.playControlFlag = 1;
    }
}

#pragma mark - 滑块拖动事件
- (void)thumbBeginScroll:(UISlider *)slider {
    
    [self.player pause];
    // 计时器暂停
    [self.timer setFireDate:[NSDate distantFuture]];
}

- (void)thumbBeingScroll:(UISlider *)slider {
    
    NSInteger minutes = slider.value / 60;
    NSInteger seconds = slider.value - minutes * 60;
    self.timesLabel.text = [NSString stringWithFormat:@"%02ld:%02ld/%02ld:%02ld", minutes, seconds, self.minutes, self.seconds];
}

- (void)thumbEndScroll:(UISlider *)slider {
    
    CMTime playFromTime = CMTimeMake(slider.value, 1);
    [self.player seekToTime:playFromTime completionHandler:^(BOOL finished) {
        
        [self.timer setFireDate:[NSDate distantPast]];
        [self.player play];
    }];
}

#pragma mark - 进度条点击手势
- (void)sliderTapAction:(UITapGestureRecognizer *)sliderTap {
    
    // 设置当前播放位置
    CGPoint point = [sliderTap locationInView:self.progressBar];
    self.progressBar.value = point.x * ((float)self.videoTimes / (float)(self.controlTable.width - 180));
    CMTime playFromTime = CMTimeMake(self.progressBar.value, 1);
    [self.player seekToTime:playFromTime];
    // 设置当前播放时间
    NSInteger minutes = self.progressBar.value / 60;
    NSInteger seconds = self.progressBar.value - minutes * 60;
    self.timesLabel.text = [NSString stringWithFormat:@"%02ld:%02ld/%02ld:%02ld",minutes, seconds, self.minutes, self.seconds];
    [self.timer setFireDate:[NSDate distantPast]];
    [self.player play];
}

#pragma mark - 退出全屏按钮
- (void)outAllScreenButtonAction {
    
    [self.player pause];
    [self.timer setFireDate:[NSDate distantFuture]];
    [self.delegate progressBarValue:self.progressBar.value withIsPlay:self.playControlFlag];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark - 本地视频播放
- (void)localVideoPlayer {
    
    NSURL *url = [NSURL fileURLWithPath:self.filePath];
    AVAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
    self.playerItem = [AVPlayerItem playerItemWithAsset:asset];
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playerLayer.frame = CGRectMake(0, 0, self.view.layer.frame.size.height, self.view.layer.frame.size.width);
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    [self.view.layer addSublayer:self.playerLayer];
    [self.player play];
    [self.timer setFireDate:[NSDate distantPast]];
    
    [self.view bringSubviewToFront:self.lumaView];
    [self.view bringSubviewToFront:self.controlTable];
    [self.view bringSubviewToFront:self.topLabel];
    [self.view bringSubviewToFront:self.rightView];
    [self.view bringSubviewToFront:self.leftView];
}

// 横屏
- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    
    return (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight);
}
- (NSUInteger)supportedInterfaceOrientations {
    
    return UIInterfaceOrientationMaskLandscapeRight;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
